<template>
	<div id="shoppingCat">
		<div class="head">
				<el-breadcrumb separator-class="el-icon-arrow-right">
					<el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
					<el-breadcrumb-item>购物车管理</el-breadcrumb-item>
				</el-breadcrumb>
				<el-button type="info" @click="logout">退出</el-button>
			</div>
		<!-- 卡片视图区 -->
		<el-card>
			<div class="shopping">
				<!-- 商品展示区域 -->
				<div class="shop" v-for="(item, i) in shops" :key="item.goodsId">
					<van-checkbox
						v-model="item.checked"
						@click="editChecked(item)"
					></van-checkbox>
					<img :src="imgUrl[i]" alt="" srcset="" />
					<div class="content">
						<h5>{{ item.goodsName }}</h5>
						<div class="msxx">
							<div v-for="o in item.onlyAttrs" v-if="o.checkeds">
								{{ o.attrName }}:{{ o.attrVals }}
							</div>
						</div>
						<div v-for="(t, index) in item.manyAttrs" :key="t.id">
							{{ t.attrName }}:{{ t.attrVals[item.manyAttrsIndex[index]] }}
						</div>

						<div class="jg">
							<span
								>￥{{
									parseFloat(item.goodsPrice * item.number).toFixed(2)
								}}</span
							>
							<van-stepper v-model="item.number" disable-input />
						</div>
						<div class="btn">
							<el-button
								type="primary"
								@click="showEditDialog(item, i)"
								icon="el-icon-edit"
								size="mini"
							></el-button>
							<el-button
								type="danger"
								@click="removeById(item)"
								icon="el-icon-delete"
								size="mini"
							></el-button>
						</div>
					</div>
				</div>
				<van-submit-bar
					:price="price"
					button-text="提交订单"
					@submit="onSubmit"
				>
					<van-checkbox v-model="checked" @click="all">全选</van-checkbox>
				</van-submit-bar>
			</div>
		</el-card>
		<van-sku
			v-model="show"
			:sku="sku"
			:goods="goods"
			:goods-id="goodsId"
			:hide-stock="true"
			@buy-clicked="onBuyClicked"
			@add-cart="onAddCartClicked"
		/>
	</div>
</template>

<script>
	export default {
		name: 'ShoppingCatVue',
		data() {
			return {
				shops: [],
				show: false,
				sku: {
					// 可以理解为一个商品可以有多个规格类目，一个规格类目下可以有多个规格值。
					tree: [],
					// 所有 sku 的组合列表，比如红色、M 码为一个 sku 组合，红色、S 码为另一个组合
					list: [],
					price: 0, // 默认价格（单位元）
					stock_num: 1, // 商品总库存
				},
				imgUrl: [],
				goods: {
					picture: require('@/assets/images/btj0iwro.png'),
					name: 'shfjs',
				},
				goodsId: '',
				id: 0,
				user: {},
			}
		},
		computed: {
			checked: {
				get() {
					var a = true
					this.shops.forEach((item) => {
						if (!item.checked) {
							a = false
						}
					})
					return a
				},
				set(value) {},
			},
			price() {
				let count = 0
				this.shops.forEach((item) => {
					if (item.checked) {
						count += item.goodsPrice * item.number
					}
				})
				return count * 100
			},
		},
		created() {
			this.processing()
		},
		methods: {
			// 退出登录
			async logout() {
				const result = await confirm('是否退出登录！')
				if (result) {
					const res = await this.$api.sort.logout()
					if (res.data.code === 1) {
						this.$message.success('退出成功！')
						this.$cookies.remove('user')
						localStorage.clear()
						this.$router.push({ path: '/' })
					} else {
						this.$message.success('退出失败！')
					}
				}
			},
			//处理数据结构
			async processing() {
				this.user = this.$cookies.get('user')
				let res = await this.$api.rear_end.allCart({ userId: this.user.userId })
				if (res.data.code == 1) {
					this.shops = res.data.data
					this.shops.forEach((item) => {
						item.manyAttrsIndex = item.manyAttrsIndex.split(' ')
						item.pics = item.pics ? item.pics.split(',') : []
						this.$api.rear_end.download(item.pics[0]).then((res) => {
							let url = window.URL.createObjectURL(
								new Blob([res.data], { type: 'image/jpeg' })
							)
							this.imgUrl.push(url)
						})
						item.manyAttrs.forEach((t) => {
							t.attrVals = t.attrVals ? t.attrVals.split(' ') : []
							t.addPrice = t.addPrice ? t.addPrice.split(' ') : []
							t.checkeds = t.checkeds ? t.checkeds.split(' ') : []
							t.manyPics = t.manyPics ? t.manyPics.split(' ') : []
							var img = []
							t.manyPics.forEach((it) => {
								if (it != 0) {
									this.$api.rear_end.download(it).then((res) => {
										let url = window.URL.createObjectURL(
											new Blob([res.data], { type: 'image/jpeg' })
										)
										img.push(url)
									})
								} else {
									img.push(0)
								}
							})
							t.manyPics = img
						})
					})
				}
			},
			all() {
				var a = !this.checked
				this.shops.forEach((item) => {
					item.checked = a
				})
			},
			onSubmit() {},
			//打开商品规格
			showEditDialog(item, goodsIndex) {
				if (this.sku.tree.length > 0) {
					this.sku.tree = []
					this.sku.list = []
				}
				this.sku.price = parseFloat(item.goodsPrice).toFixed(2)
				this.goodsId = item.goodsId
				this.goods.picture=this.imgUrl[goodsIndex]
				this.sku.stock_num = item.goodsNumber
				item.manyAttrs.forEach((t, i) => {
					var tree1 = {
						k: t.attrName,
						k_s: t.id,
						v: [],
						largeImageMode: false,
					}
					t.attrVals.forEach((a, index) => {
						var v1 = {
							id: index,
							name: a,
						}
						if (t.manyPics[index] != 0) {
							v1.imgUrl = t.manyPics[index]
							v1.previewImgUrl = t.manyPics[index]
						}
						tree1.v.push(v1)
					})
					this.sku.tree.push(tree1)
				})
				this.combination(0, {}, this.sku.tree, goodsIndex)
				this.show = true
			},
            //处理属性组合函数
			combination(index, t1, arr, goodsIndex) {
				if (index == arr.length) {
					return
				}			
				for (let i = 0; i < arr[index].v.length; i++) {
					t1[arr[index].k_s] = arr[index].v[i].id
					t1.id = this.id
					t1.stock_num = this.shops[goodsIndex].goodsNumber
					t1.price = (this.sku.price) * 100+parseInt(this.shops[goodsIndex].manyAttrs[index].addPrice[i])*100
					t1.goodsIndex = goodsIndex
					let newT1 = { ...t1 } // 创建 t1 的副本
					if (index == arr.length - 1) {
						this.sku.list.push(newT1)
					}
					this.id += 1
					this.combination(index + 1, t1, arr, goodsIndex)
				}
			},

			
			// 点击删除购物车
			removeById(item) {
				this.$confirm('确认删除该商品的购物车吗？')
					.then(async (_) => {
						let res = await this.$api.rear_end.delCart({
							id: item.shoppingId,
						})
						if (res.data.code == 1) {
							this.$message.success(res.data.data)
							this.processing()
							return
						}
						this.$message.error(res.data.data)
					})
					.catch(async (_) => this.$message.warning('取消操作'))
			},
			//点击购买回调
			onBuyClicked() {},
			//点击添加购物车回调
			async onAddCartClicked(skuData) {
				var selectedNum = skuData.selectedNum
				var selectedSkuComb = skuData.selectedSkuComb
				var index = selectedSkuComb.goodsIndex
				this.shops[index].number = selectedNum
				var price = 0
				this.shops[index].manyAttrs.forEach((item, i) => {
					this.shops[index].manyAttrsIndex[i] = selectedSkuComb[item.id]
					price +=parseInt(item.addPrice[selectedSkuComb[item.id]]) 
				})
				price += this.shops[index].goodsPrice
				var manyAttrsIndex=this.shops[index].manyAttrsIndex.join(" ")
				let res = await this.$api.rear_end.editCart({
					shoppingId: this.shops[index].shoppingId,
					goodsId: this.shops[index].goodsId,
					number: this.shops[index].number,
					totalPice: price,
					userId:this.shops[index].userId,
					manyAttrsIndex:manyAttrsIndex,
					checked:this.shops[index].checked
				})
				if (res.data.code == 1) {
					this.$message.success(res.data.data)
					this.processing()
					this.show = false
					return
				}
				this.$message.error(res.data.data)
				this.show = false
			},
			// 修改购物车选中状态
		async	editChecked(item){
				let res = await this.$api.rear_end.editCart({
					shoppingId: item.shoppingId,
					checked:item.checked
				})
				if (res.data.code == 1) {
					this.$message.success(res.data.data)
					return
				}
				this.$message.error(res.data.data)
			}
		},
	}
</script>

<style lang="less" scoped>
	#shoppingCat {
		.head {
			
			.el-breadcrumb{
				float: left;
				font-size: 2rem;
				
			} 
			.el-button{
				float: right;
			}
			padding-bottom: 10vh;
		}
		.el-card {
			.shopping {
				display: flex;
				flex-direction: column;
				.shop {
					background-color: #f5f5f5;
					display: flex;
					align-items: center;
					margin: 10px 0;
					box-shadow: 0 10px 10px #ccc;
					border-radius: 12px;
					.van-checkbox {
						margin-left: 20px;
						margin-right: 20px;
					}
					img {
						width: 10%;
						height: 10%;
						object-fit: fill;
					}
					.content {
						display: flex;
						flex-direction: column;
						padding: 2rem 0 2rem 2rem;
						width: 80%;
						h5 {
							font-size: 1.6rem;
							margin-left: -12px;
						}
						.msxx {
							display: flex;
							> div {
								margin-left: 20px;
								font-size: 1.4rem;
								&:first-child {
									margin-left: 0px;
								}
							}
						}
						.jg {
							display: flex;
							justify-content: space-between;
							span {
								font-size: 1.2rem;
								color: #fc5131;
							}
						}
						.btn {
							display: flex;
							justify-content: flex-end;
							margin-top: 20px;
						}
					}
				}

				.van-submit-bar {
					position: relative;
					margin-top: 20px;
				}
			}
		}
	}
</style>